#include "Temperature_logger.h"

// declare global variables 
volatile char KEY = 0;
volatile char KEY_VALID = 0; 
volatile char ENABLED = 0;

extern  volatile unsigned char KEY_PRESSED ;
extern  volatile unsigned char PRESENT_KEY ;
extern  volatile char VALID_KEY_PRESSED;

extern volatile unsigned int KEY_PRESS_DURATION_COUNT;

void Enable_Joystick (void)
{
DDRB |= 0xD8;
PORTB |= PINB_MASK;
DDRE |= 0x00;
PORTE |= PINE_MASK;
PCMSK0 = PINE_MASK;
PCMSK1 = PINB_MASK;
EIFR = (1<<6) | (1<<7);
EIMSK = (1<<6) | (1<<7);
DDRB = 0x00;
PORTB = 0xFF;

if (ENABLED == 0)
	ENABLED = 1;
else 
	ENABLED = 0;

sei();
}

/*
void Disable_Joystick (void)
{
DDRB|=PINB_MASK;
PORTB|=~PINB_MASK;
DDRE|=PINE_MASK;
PORTE|=~PINE_MASK;
EIMSK = (0<<6) | (0<<7);
KEY_PRESSED=KEY_INVALID;
PRESENT_KEY=KEY_INVALID;
KEY_PRESS_DURATION_COUNT=0;
}
*/
void Disable_Joystick (void)
{EIMSK = (0<<6) | (0<<7);
}

SIGNAL(SIG_PIN_CHANGE0)
{
PinChangeInterrupt();
}

SIGNAL(SIG_PIN_CHANGE1)
{
PinChangeInterrupt();
}

void PinChangeInterrupt(void)
{ 
	char buttons;
	char key;
	buttons = (~PINB) & PINB_MASK;
	buttons |= (~PINE) & PINE_MASK;
	if (buttons & (1<<BUTTON_A))
		key = KEY_UP;
	else if (buttons & (1<<BUTTON_B))
		key = KEY_DOWN;
	else if (buttons & (1<<BUTTON_C)) 
		key = KEY_LEFT;
	else if (buttons & (1<<BUTTON_D)) 
		key = KEY_RIGHT; 
	else if (buttons & (1<<BUTTON_O))
		key = KEY_PUSH;
	else
		key = KEY_INVALID;


	if (key != KEY_INVALID)
	{
		if(!KEY_VALID)
		{
			KEY = key;
			KEY_VALID = TRUE;
			Ena_Key_Press_Dur_Count();
		}
	}
	else
		Dis_Key_Press_Dur_Count();

	EIFR = (1<<PCIF1) | (1<<PCIF0);

	if (ENABLED)
	{
		getkey();
	}
}

char getkey(void)
{
	char k;
	cli();
	if(KEY_VALID)
	{
		k = KEY;
		KEY_VALID = FALSE;
		KEY_PRESSED = k;
	}
	else
	{
	k = KEY_INVALID;
	}
	
	PRESENT_KEY=k;
	
	Key_Debounce();
	
	sei();

return k;
}

void Key_Debounce (void)
{
	static unsigned char Key_Validated = 0;
	if (KEY_PRESSED!=PRESENT_KEY)
		{
		if (Key_Validated==1)
			{
			VALID_KEY_PRESSED=KEY_PRESSED;
			Key_Validated=0;
			}
		else Key_Validated==0;
		}
	else if (KEY_PRESSED==KEY_INVALID)
		{
		Key_Validated = 0;
		VALID_KEY_PRESSED = KEY_INVALID;
		}
	else if (KEY_PRESSED==PRESENT_KEY)
		{
		Key_Validated = 1;
		VALID_KEY_PRESSED = KEY_INVALID;
		}
	else 
		{
		Key_Validated = 0;
		VALID_KEY_PRESSED = KEY_INVALID;
		}
}